import React, {
    Component
} from 'react';
import RNFetchBlob from "react-native-fetch-blob";
import {
    CameraRoll,
    Alert
} from 'react-native';

class DownloadUtil {

    /**
     * 保存网络图片到相册
     * @param imageUrl 图片url
     */
    saveImageAlbum(imageUrl) {

        if (imageUrl.length > 0) {
            RNFetchBlob.config({
                    // add this option that makes response data to be stored as a file,
                    // this is much more performant.
                    fileCache: true,
                    appendExt: 'png'
                })
                .fetch('GET', imageUrl, {

                    //some headers ..
                })
                .then((res) => {
                    // the temp file path
                    CameraRoll.saveToCameraRoll(res.path()).then(() => {
                        Alert.alert('', '保存成功!');
                        this.deleteCacheImage(res.path());
                    }).catch((err) => {
                        this.deleteCacheImage(res.path());
                    });
                })
        }
    }

    /**
     * 删除缓存图片
     * @param path
     */
    deleteCacheImage(path) {
        RNFetchBlob.fs.unlink(path).then(() => {
            // console.warn('Deleted successfully')
        })
    }


}

export default new DownloadUtil();